package cn.jiadakeji.parent.service;

import cn.jiadakeji.parent.common.constant.Constants;
import cn.jiadakeji.parent.dto.CustomerJwtDTO;

import cn.jiadakeji.parent.dto.LoginRetDTO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author hhaoyu
 */
@Service
public class TokenService {

    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;


    @Value("${token.accessTokenExpireTime}")
    private int accessTokenExpireTime;

    @Value("${token.refreshTokenExpireTime}")
    private int refreshTokenExpireTime;




    public LoginRetDTO login(CustomerJwtDTO customerJwtDTO){
        LoginRetDTO loginRetDTO = new LoginRetDTO();
        loginRetDTO.setAccessToken(createToken(customerJwtDTO));
        Map<String, Object> refreshTokenGet = new HashMap<String, Object>();
        refreshTokenGet.put("customerId", customerJwtDTO.getId());
        String refreshToken = createToken(refreshTokenGet, getExpDate(refreshTokenExpireTime));
        loginRetDTO.setRefreshToken(refreshToken);
        loginRetDTO.setOpenId(customerJwtDTO.getOpenId());
        return loginRetDTO;
    }


    /**
     * 创建令牌
     *
     * @param customer 用户信息
     * @return 令牌
     */
    public String createToken(CustomerJwtDTO customer) {

        Map<String, Object> claims = new HashMap<String, Object>(5);
        claims.put("id", customer.getId());
        claims.put("phone", customer.getPhone());
        claims.put("openId", customer.getOpenId());
        claims.put("customerParentPartId",customer.getCustomerParentPartId());
        claims.put("studentParentId",customer.getStudentParentId());
        return createToken(claims, getExpDate(accessTokenExpireTime));
    }

    private Date getExpDate(int second){
        long now = System.currentTimeMillis();
        return new Date(now + getTimeMilliSecond(second));
    }
    private long getTimeMilliSecond(int second){
        return (long) second * 60 * 1000;
    }




    public String createToken(Map<String, Object> claims, Date exp) {

        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS256, secret)
                .setExpiration(exp)
                .compact();
        return token;
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    public CustomerJwtDTO getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            try {
                Claims claims = parseToken(token);
                CustomerJwtDTO customerJwtDTO = new CustomerJwtDTO();
                customerJwtDTO.setId((String)claims.get("id"));
                customerJwtDTO.setPhone((String)claims.get("phone"));
                customerJwtDTO.setOpenId((String)claims.get("openId"));
                customerJwtDTO.setCustomerParentPartId((String) claims.get("customerParentPartId"));
                customerJwtDTO.setStudentParentId((String) claims.get("studentParentId"));
                return customerJwtDTO;
            } catch (Exception ignored) {

            }
        }
        return null;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    public Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }


    public String getCustomerIdFromRefreshToken(String refreshToken){
        try {
            Claims claims = parseToken(refreshToken);
            return (String)claims.get("customerId");
        }catch (Exception e){

        }
        return null;
    }



}
